package com.feihong.txgw.ui.activity.kaika;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.KeyboardUtils;
import com.feihong.txgw.R;
import com.feihong.txgw.inter.contract.kaika.IKaikaContract;
import com.feihong.txgw.json.kaika.ICCIDList;
import com.feihong.txgw.message.LoginMessage;
import com.feihong.txgw.tx_precenter.KaikaMainPrecenter;
import com.feihong.txgw.ui.mvp.BaseMVPCompateActivity;
import com.feihong.txgw.ui.mvp.precenter.AbBasePrecenter;
import com.feihong.txgw.view.ICCIDListPopupWindow;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Created by Sabirjan on 2017/6/29.
 * TXGWApp.  待优化  无数据时的界面状态
 * 飞宏电子
 * 开卡页面
 */

public class KaiKaActivity extends BaseMVPCompateActivity<IKaikaContract.AbKaikaMainPrecenter> implements AdapterView.OnItemClickListener, View.OnClickListener, IKaikaContract.IKaikaMainView {

    /**
     * 传递的ICCID
     */
    public static final String INTENT_ICCID = "intent_iccid";
    /**
     * 传递的order_sn
     */
    public static final String INTENT_ORDERSN = "intent_ordersn";
    /**
     * 订单列表传来的 fromBooking
     */
    public static final String INTENT_FROM_BOOKING = "INTENT_FROM_BOOKING";
    /**
     * 传递的PhoneNum 第二步骤-》第三步骤
     */
    public static final String INTENT_PHOE_NUM = "intent_phonenum";
    /**
     * 传递的PhoneNum_iD 第二步骤-》第三步骤
     */
    public static final String INTENT_PHOE_NUM_ID = "intent_phonenum_id";


    private static final int REQUEST_CODE = 9991;
    private static final int SUCCESS_CODE = 1;
    private static final int ICCID_STATE_NORMAL = 100;
    private static final int ICCID_STATE_ERROR = -100;
    /**
     * 后七位列表失败状态
     */
    private static final int ICCID_LIST_STATE_ERROR = -200;
    /**
     * 后七位列表成功状态
     */
    private static final int ICCID_LIST_STATE_NORMAL = 200;


    @BindView(R.id.lay_iccid)
    RelativeLayout layIccid;
    @BindView(R.id.txt_iccid_lastnum)
    TextView txtIccidLastnum;
    @BindView(R.id.edit_iccid_lastnum)
    EditText editIccidLastnum;
    @BindView(R.id.lay_iccid_selected)
    RelativeLayout layIccidSelected;
    @BindView(R.id.txt_iccid_selectednum)
    TextView txtIccidSelectednum;
    @BindView(R.id.edit_iccid_selected)
    EditText editIccidSelected;
    @BindView(R.id.btn_next)
    Button btn_next;
    @BindView(R.id.iv_progress)
    ProgressBar iv_progress;
    @BindView(R.id.btn_lastnum_scan)
    ImageButton mScan;
    @BindView(R.id.guide_input_iccid_type)
    ImageView mInputIccidType;
    @BindView(R.id.kaika_layout)
    LinearLayout mKaikaLayout;
    @BindView(R.id.connect_net_error_layout)
    LinearLayout mConnectErrorLayout;
    @BindView(R.id.lay_loading)
    RelativeLayout mLoadingLayout;
    @BindView(R.id.re_query_data_layout)
    LinearLayout mQueryDataAgagin;
    @BindView(R.id.blew_btn_lastnum_scan)
    ImageButton mBlewScan;
    @BindView(R.id.kaika_sm_devider)
    View mSmDevide;
    /**
     * 选择的ICCID
     */
    private String selected_iccid = "";
    /**
     * ICCID是否选择成功
     */
    private boolean selected_success = false;
    private String lastNum = "";
    private ICCIDListPopupWindow iccidListPopupWindow;
    private List<ICCIDList.DataBean> items;

    private int mFromBooking = 0;
    private String mOrderListPutOrderSn;

    @Override
    public void setTheme() {

    }

    @Override
    public int setLayoutID() {
        return R.layout.activity_kaika;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        KaikaManager.getmKaikaManager().addStack(this);
        items = new ArrayList<>();
        iccidListPopupWindow = new ICCIDListPopupWindow(this);
        iccidListPopupWindow.setListener(this);
        Intent orderIntent = getIntent();
        if (orderIntent != null) {
            mOrderListPutOrderSn = orderIntent.getStringExtra(INTENT_ORDERSN);
            mFromBooking = orderIntent.getIntExtra(INTENT_FROM_BOOKING, 0);
        }
        mKaikaLayout.setVisibility(View.GONE);
        setPageTitle("持卡卡户");
    }

    /**
     * 获取iccid的方式
     */
    private void queryICCIDType() {
        mLoadingLayout.setVisibility(View.VISIBLE);
        mPresenter.getQueryICCIDType();
    }
    private Drawable mICCIDTypeDrawable;

    private void addTextListener() {
        editIccidLastnum.addTextChangedListener(mTextWatcher);
    }

    TextWatcher mTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (s != null && s.toString().trim().length() == 7) {
                iv_progress.setVisibility(View.VISIBLE);
                KeyboardUtils.hideSoftInput(getActivity());
                getICCIDList(s.toString());
                lastNum = s.toString();
            } else if (!selected_success) {
                btn_next.setEnabled(false);
            }

            if (s != null && s.toString().trim().length() != 7) {
                btn_next.setEnabled(false);
                editIccidSelected.setText("");
            }
        }
    };

    private void removeTextListener() {
        editIccidLastnum.removeTextChangedListener(mTextWatcher);
    }

    /**
     * 扫码按钮点击事件
     */
    public void btnSaoMaClick(View view) {
        KeyboardUtils.hideSoftInput(this);
        startNewActivityForResult(ScanBarCodeActivity.class,null, REQUEST_CODE);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE) {
            if (resultCode == SUCCESS_CODE && data != null) {
                String number = data.getStringExtra("result");
                if (number != null && number.trim().length() > 18) {
                    String lastNum = "";
                    lastNum = number.substring(number.length() - 7);
                    editIccidSelected.setText(number);
                    removeTextListener();
                    editIccidLastnum.setText(lastNum);
                    addTextListener();
                    getICCIDList(number);
                } else {
                    showSystemToast("扫码出来的数据有误！");
                }
            }
        }
    }

    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            if (activityIsDestory()) {
                return;
            }
            iv_progress.setVisibility(View.INVISIBLE);
            if (msg.what == ICCID_STATE_NORMAL) {
                showSystemToast("验证ICCID成功！");
                Bundle bundle = msg.getData();
                selected_iccid = bundle.getString("iccid");
                selected_success = true;
                btn_next.setEnabled(true);

            } else if (msg.what == ICCID_STATE_ERROR) {
                showSystemToast(msg.obj.toString());
                selected_iccid = "";
                selected_success = false;
                btn_next.setEnabled(false);

            } else if (msg.what == ICCID_LIST_STATE_NORMAL) {
                if (msg.obj != null) {
                    items = (ArrayList<ICCIDList.DataBean>) msg.obj;
                    iccidListPopupWindow.setData(items);
                    iccidListPopupWindow.show(editIccidLastnum);
                }

            } else if (msg.what == ICCID_LIST_STATE_ERROR) {
                showSystemToast(msg.obj.toString());
                selected_iccid = "";
                selected_success = false;
                btn_next.setEnabled(false);
                editIccidSelected.setText("");
            }
        }
    };

    /**
     * 获取ICCID匹配的列表
     *
     * @param lastNumber ICCID后七位
     */
    private void getICCIDList(String lastNumber) {
        showProgressDialog("正在验证ICCID...");
        mPresenter.loadICCIDListOrValiData(lastNumber, mOrderListPutOrderSn);
    }

    /**
     * 下一步按钮的点击事件
     */
    public void btnNextClick(View view) {

        if (selected_iccid != null && selected_iccid.trim().length() > 0 && selected_success) {
            Intent intent = new Intent();
            if (TextUtils.isEmpty(mOrderListPutOrderSn)) {
                intent.setClass(this, KaiKaStep2Activity.class);
                intent.putExtra(INTENT_ICCID, selected_iccid);
            } else {
                intent.setClass(this, KaiKaStep4Activity.class);
                intent.putExtra(INTENT_ORDERSN, mOrderListPutOrderSn);
                intent.putExtra(INTENT_FROM_BOOKING, mFromBooking);
                intent.putExtra(INTENT_ICCID, selected_iccid);
            }
            startActivity(intent);
        }

    }

    @Override
    public void bindData() {
        super.bindData();
        mQueryDataAgagin.setOnClickListener(this);
        setBackButtonFinish();
        addTextListener();
        queryICCIDType();
    }

    @Override
    public void onUserLogin(LoginMessage loginMessage) {

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        KeyboardUtils.hideSoftInput(this);
        iccidListPopupWindow.dismiss();
        if (this.items != null && this.items.size() > position) {
            String number = items.get(position).getIccid_no();
            if (number != null && number.trim().length() > 18) {
                editIccidSelected.setText(number);
                selected_iccid = number;
                selected_success = true;
                btn_next.setEnabled(true);
            } else {
                showSystemToast("选择的数据有误！");
            }
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.re_query_data_layout:
                mConnectErrorLayout.setVisibility(View.GONE);
                queryICCIDType();
                break;
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mHandler != null && mHandler.getLooper() == Looper.getMainLooper()) {
            mHandler.removeCallbacksAndMessages(null);
        }
    }

    @Override
    public void setICCIDTypeResult(String type) {
        mKaikaLayout.setVisibility(View.VISIBLE);
        mInputIccidType.setVisibility(View.VISIBLE);
        mKaikaLayout.setVisibility(View.VISIBLE);
        switch (type) {
            case "1":
                // 只能手动输入
                mSmDevide.setVisibility(View.VISIBLE);
                layIccid.setVisibility(View.VISIBLE);
                mICCIDTypeDrawable = getResources().getDrawable(R.mipmap.input_iccid_type_one);
                mInputIccidType.setImageDrawable(mICCIDTypeDrawable);
                break;
            case "2":
                // 可扫码 也可手动输入
                mSmDevide.setVisibility(View.VISIBLE);
                layIccid.setVisibility(View.VISIBLE);
                mICCIDTypeDrawable = getResources().getDrawable(R.mipmap.input_iccid_type_two);
                mInputIccidType.setImageDrawable(mICCIDTypeDrawable);
                mScan.setVisibility(View.VISIBLE);
                editIccidLastnum.setEnabled(true);
                break;
            case "3":
                // 只能扫码
                mSmDevide.setVisibility(View.GONE);
                mBlewScan.setVisibility(View.VISIBLE);
                layIccid.setVisibility(View.GONE);
                mScan.setVisibility(View.VISIBLE);
                mICCIDTypeDrawable = getResources().getDrawable(R.mipmap.input_iccid_type_three);
                mInputIccidType.setImageDrawable(mICCIDTypeDrawable);
                break;
            default:
                break;
        }
    }

    @Override
    public void setValiResult(String iccid) {
        selected_iccid = iccid;
        selected_success = true;
        btn_next.setEnabled(true);
    }

    @Override
    public void setValiResultError(String msg) {
        dismissProgressDialog();
        String errorMsg;
        if (TextUtils.isEmpty(msg)) {
            errorMsg = getString(R.string.connect_service_error);
        } else {
            errorMsg = msg;
        }
        showSystemToast(errorMsg);
        iv_progress.setVisibility(View.GONE);
        selected_iccid = "";
        selected_success = false;
        btn_next.setEnabled(false);
    }

    @Override
    public void setICCIDList(ICCIDList iccidList) {
        items = iccidList.getData();
        iccidListPopupWindow.setData(items);
        iccidListPopupWindow.show(editIccidLastnum);
    }

    @Override
    public void loadDataComplated() {
        iv_progress.setVisibility(View.GONE);
        mLoadingLayout.setVisibility(View.GONE);
        dismissProgressDialog();
    }

    @Override
    public void loadDataError() {
        dismissProgressDialog();
        mLoadingLayout.setVisibility(View.GONE);
        mConnectErrorLayout.setVisibility(View.VISIBLE);
        mKaikaLayout.setVisibility(View.GONE);
    }

    @NonNull
    @Override
    public AbBasePrecenter initPresenter() {
        return KaikaMainPrecenter.create();
    }
}
